/**
 * 智慧农业系统主题样式自动应用脚本
 * 
 * 此脚本用于自动向组件添加农业主题的样式类
 * 使用方法：在命令行中运行 node apply-theme.js <文件路径>
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 需要添加的样式类映射
const classMap = {
  // 容器类
  'dashboard-container': 'agri-page-container',
  'profile-container': 'agri-page-container',
  'land-management-container': 'agri-page-container',
  'planting-management-container': 'agri-page-container',
  'fertilizer-management-container': 'agri-page-container',
  'inventory-management-container': 'agri-page-container',
  'product-management-container': 'agri-page-container',
  'order-management-container': 'agri-page-container',
  'sales-record-container': 'agri-page-container',
  'farmer-trade-container': 'agri-page-container',
  'complaint-management-container': 'agri-page-container',
  'farmer-list-container': 'agri-page-container',
  'create-order-container': 'agri-page-container',
  'seller-order-management-container': 'agri-page-container',
  
  // 头部类
  'page-header': 'agri-page-header',
  'page-title': 'agri-page-title',
  'page-actions': 'agri-page-actions',
  
  // 卡片类
  'stats-card': 'agri-card',
  'list-card': 'agri-card',
  'chart-card': 'agri-card',
  'data-card': 'agri-card',
  'filter-card': 'agri-card',
  'info-card': 'agri-card',
  'user-card': 'agri-card',
  'main-card': 'agri-card',
  'actions-card': 'agri-card',
  'map-card': 'agri-card',
};

// 自动添加类的正则表达式
const containerRegex = /<div class="([^"]*-container)([^"]*)"/g;
const headerRegex = /<div class="([^"]*page-header)([^"]*)"/g;
const titleRegex = /<div class="([^"]*page-title)([^"]*)"/g;
const actionsRegex = /<div class="([^"]*page-actions)([^"]*)"/g;
const cardRegex = /<el-card([^>]*class="[^"]*card[^"]*")([^>]*)>/g;
const simpleCardRegex = /<el-card([^>]*)>/g;

// 添加表格包装和对话框包装
const tableRegexps = [
  /<el-table([^>]*)>/g,
  /<\/el-table>/g
];

const dialogRegexps = [
  /<el-dialog([^>]*)>/g,
  /<\/el-dialog>/g
];

// 添加操作按钮包装
const operationsRegex = /<template #default="scope">\s*<el-button/g;

/**
 * 处理文件内容，添加主题样式类
 * @param {string} content 文件内容
 * @returns {string} 处理后的内容
 */
function processContent(content) {
  // 添加容器类
  content = content.replace(containerRegex, (match, className, rest) => {
    const agrClass = classMap[className];
    if (agrClass && !match.includes(agrClass)) {
      return `<div class="${className}${rest} ${agrClass}"`;
    }
    return match;
  });
  
  // 添加头部类
  content = content.replace(headerRegex, (match, className, rest) => {
    const agrClass = classMap['page-header'];
    if (agrClass && !match.includes(agrClass)) {
      return `<div class="${className}${rest} ${agrClass}"`;
    }
    return match;
  });
  
  // 添加标题类
  content = content.replace(titleRegex, (match, className, rest) => {
    const agrClass = classMap['page-title'];
    if (agrClass && !match.includes(agrClass)) {
      return `<div class="${className}${rest} ${agrClass}"`;
    }
    return match;
  });
  
  // 添加操作类
  content = content.replace(actionsRegex, (match, className, rest) => {
    const agrClass = classMap['page-actions'];
    if (agrClass && !match.includes(agrClass)) {
      return `<div class="${className}${rest} ${agrClass}"`;
    }
    return match;
  });
  
  // 添加卡片类
  content = content.replace(cardRegex, (match, classAttr, rest) => {
    if (!classAttr.includes('agri-card')) {
      return match.replace(classAttr, classAttr + ' agri-card');
    }
    return match;
  });
  
  // 处理没有class属性的卡片
  content = content.replace(simpleCardRegex, (match, rest) => {
    if (!match.includes('class="') && !match.includes('agri-card')) {
      return match.replace('>', ' class="agri-card">');
    }
    return match;
  });
  
  // 表格包装
  let lines = content.split('\n');
  let inTable = false;
  let tableStartIndex = -1;
  
  for (let i = 0; i < lines.length; i++) {
    if (!inTable && lines[i].match(/<el-table([^>]*)>/)) {
      // 检查是否已经有agri-table-wrapper包装器，需要检查父级元素(前一行或当前行)
      const hasWrapper = 
        (i > 0 && lines[i-1].includes('agri-table-wrapper')) || 
        lines[i].match(/<div[^>]*class="[^"]*agri-table-wrapper[^"]*"[^>]*>/);
      
      if (!hasWrapper) {
        lines.splice(i, 0, '<div class="agri-table-wrapper">');
        tableStartIndex = i;
        inTable = true;
        i++;
      } else {
        // 已有包装器，只记录我们在表格内
        inTable = true;
      }
    } else if (inTable && lines[i].match(/<\/el-table>/)) {
      // 检查表格后是否已经有关闭的div
      const hasClosingDiv = 
        (i < lines.length - 1 && lines[i+1].includes('</div>')) || 
        lines[i].includes('</el-table></div>');
      
      if (!hasClosingDiv && tableStartIndex > -1) {
        lines.splice(i+1, 0, '</div>');
        inTable = false;
        i++;
      } else {
        // 已有关闭标签，只记录我们离开表格
        inTable = false;
      }
    }
  }
  
  // 对话框包装
  content = lines.join('\n');
  lines = content.split('\n');
  let inDialog = false;
  let dialogStartIndex = -1;
  
  for (let i = 0; i < lines.length; i++) {
    if (!inDialog && lines[i].match(/<el-dialog([^>]*)>/)) {
      // 检查是否已经有agri-dialog-wrapper包装器
      const hasWrapper = 
        (i > 0 && lines[i-1].includes('agri-dialog-wrapper')) || 
        lines[i].match(/<div[^>]*class="[^"]*agri-dialog-wrapper[^"]*"[^>]*>/);
      
      if (!hasWrapper) {
        lines.splice(i, 0, '<div class="agri-dialog-wrapper">');
        dialogStartIndex = i;
        inDialog = true;
        i++;
      } else {
        // 已有包装器，只记录我们在对话框内
        inDialog = true;
      }
    } else if (inDialog && lines[i].match(/<\/el-dialog>/)) {
      // 检查对话框后是否已经有关闭的div
      const hasClosingDiv = 
        (i < lines.length - 1 && lines[i+1].includes('</div>')) || 
        lines[i].includes('</el-dialog></div>');
      
      if (!hasClosingDiv && dialogStartIndex > -1) {
        lines.splice(i+1, 0, '</div>');
        inDialog = false;
        i++;
      } else {
        // 已有关闭标签，只记录我们离开对话框
        inDialog = false;
      }
    }
  }
  
  // 操作按钮包装
  content = lines.join('\n');
  content = content.replace(operationsRegex, '<template #default="scope">\n        <div class="agri-operations">\n          <el-button');
  
  // 处理操作按钮的闭合标签
  content = content.replace(/(<\/el-button>\s*)(<\/template>)/g, '$1\n        </div>\n      $2');
  
  return content;
}

/**
 * 处理单个文件
 * @param {string} filePath 文件路径
 */
function processFile(filePath) {
  try {
    console.log(`处理文件: ${filePath}`);
    const content = fs.readFileSync(filePath, 'utf8');
    const processedContent = processContent(content);
    
    if (content !== processedContent) {
      fs.writeFileSync(filePath, processedContent, 'utf8');
      console.log(`已更新文件: ${filePath}`);
    } else {
      console.log(`文件无需更新: ${filePath}`);
    }
  } catch (error) {
    console.error(`处理文件 ${filePath} 时出错:`, error);
  }
}

/**
 * 递归处理目录
 * @param {string} dir 目录路径
 * @param {RegExp} filter 文件过滤正则表达式
 */
function processDirectory(dir, filter) {
  const files = fs.readdirSync(dir);
  
  for (const file of files) {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isDirectory()) {
      // 排除auth目录
      if (file !== 'auth') {
        processDirectory(filePath, filter);
      } else {
        console.log(`跳过登录/注册目录: ${filePath}`);
      }
    } else if (stat.isFile() && filter.test(file)) {
      processFile(filePath);
    }
  }
}

// 主函数
function main() {
  const args = process.argv.slice(2);
  const viewsDir = path.resolve(__dirname, '../views');
  
  if (args.length > 0) {
    // 处理单个文件
    const filePath = path.resolve(args[0]);
    if (fs.existsSync(filePath)) {
      processFile(filePath);
    } else {
      console.error(`文件不存在: ${filePath}`);
    }
  } else {
    // 处理所有Vue文件
    console.log(`处理目录: ${viewsDir}`);
    processDirectory(viewsDir, /\.vue$/);
  }
}

// 执行主函数
main(); 